package BandB.Tool.GPhoneManager.TaskManager;

import java.io.FileNotFoundException;
import java.util.HashMap;

import org.dom4j.DocumentException;
import org.xmlpull.v1.XmlPullParserException;

import BandB.Tool.GPhoneManager.R;
import BandB.Tool.GPhoneManager.TaskManager.config.XmlManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class TimeSetting extends Activity implements OnClickListener {

	private static final String TAG = "TimeSetting";
	// private ImageView imageRunningView;
	private View showTimespanView;
	private View showEveryDayView;
	private CheckBox checkTimespan, checkEverday;
	private EditText eTextHours;
	private EditText eTextMins;
	private EditText eTextEverydayH;
	private EditText eTextEverydayM;
	// private Animation runningAnimation;
	private Button btnOK, btnCancel;

	private XmlManager xmlManager;

	private static byte CURRENT_MODE = -1;
	private static String CURRENT_TYPE;
	private static final byte MODE_TIMESPAN = 0;
	private static final byte MODE_EVERDAY = 1;
	public static final String GET_SETTING = "input";

	public static final int SHORTEST_TIMESPAN_MINS = 15;
	public static final int LONGEST_TIMESPAN_MINS = 59;
	public static final int LONGEST_TIMESPAN_HOURS = 23;

	// private static final byte RESULT_TOO_BIG = 1;
	private static final byte RESULT_TOO_SMALL = -1;
	private static final byte RESULT_RIGHT = 0;
	private static final byte RESULT_INPUT_ERROR = 2;
	protected static final int MSG_FINISH_ACTIVITY = 128;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set_timespan);
		initViewStatus();
		setStatusForEditText();
	}

	private void setStatusForEditText() {
		try {
			xmlManager = new XmlManager(this);
		} catch (Exception e) {
			return;
		}
		HashMap<String, String> configMap = xmlManager.readConfig();
		String type, value;
		if (null != configMap && 0 != configMap.size()) {
			type = configMap.get(XmlManager.ELEMENT_TYPE);
			value = configMap.get(XmlManager.ELEMENT_VALUE);

			if (type.equals(XmlManager.TYPE_TIME_SPAN)) {
				CURRENT_MODE = MODE_TIMESPAN;
				String[] tempStrings = value.split(XmlManager.SPLIT);
				eTextHours.setText(tempStrings[0]);
				eTextMins.setText(tempStrings[1]);
			} else {
				if (type.equals(XmlManager.TYPE_EVERYDAY_TIME)) {
					CURRENT_MODE = MODE_EVERDAY;
					String[] tempStrings = value.split(XmlManager.SPLIT);
					eTextEverydayH.setText(tempStrings[0]);
					eTextEverydayM.setText(tempStrings[1]);
				} else {
					Log.e(TAG, "get config from local error.");
				}
			}
		} else {
			Log.e(TAG, "no config file in local, use the default config.");
			eTextHours.setText("24");
			eTextMins.setText("00");
			// current_type = XmlManager.TYPE_TIME_SPAN;
			CURRENT_MODE = MODE_TIMESPAN;
			return;
		}
	}

	private void initViewStatus() {
		// imageRunningView = (ImageView) findViewById(R.id.imageRunningView);
		showTimespanView = findViewById(R.id.showTimespanView);
		showEveryDayView = findViewById(R.id.showEveryDayView);
		eTextHours = (EditText) findViewById(R.id.editTextHours);
		eTextMins = (EditText) findViewById(R.id.editTextMins);
		eTextEverydayH = (EditText) findViewById(R.id.editTextHourEverday);
		eTextEverydayM = (EditText) findViewById(R.id.editTextMinEverday);
		eTextHours.setOnFocusChangeListener(onFocusChangeListener);
		eTextMins.setOnFocusChangeListener(onFocusChangeListener);
		eTextEverydayH.setOnFocusChangeListener(onFocusChangeListener);
		eTextEverydayM.setOnFocusChangeListener(onFocusChangeListener);
		btnOK = (Button) findViewById(R.id.btnSetOK);
		btnOK.setOnClickListener(this);
		btnCancel = (Button) findViewById(R.id.btnSetCancel);
		btnCancel.setOnClickListener(this);

		checkTimespan = (CheckBox) findViewById(R.id.settingCheckTimespan);
		checkEverday = (CheckBox) findViewById(R.id.settingCheckEverday);
	}

	OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			// TODO Auto-generated method stub
			if (!hasFocus) {
				return;
			}
			switch (v.getId()) {
			case R.id.editTextHourEverday:
				setMode(MODE_EVERDAY);
				break;
			case R.id.editTextMinEverday:
				setMode(MODE_EVERDAY);
				break;
			case R.id.editTextHours:
				setMode(MODE_TIMESPAN);
				break;
			case R.id.editTextMins:
				setMode(MODE_TIMESPAN);
				break;
			default:
				break;
			}
		}

	};

	/**
	 * check user's input when user click the OK button
	 * 
	 * @return result recognized by user(big, small, OK, etc.)
	 */
	private byte checkInput() {
		switch (CURRENT_MODE) {
		case MODE_TIMESPAN:
			int timespan_hours,
			timespan_mins;
			try {
				timespan_hours = Integer.parseInt(eTextHours.getText()
						.toString());
			} catch (Exception e) {
				// TODO: handle exception
				timespan_hours = 0;
			}
			try {
				timespan_mins = Integer
						.parseInt(eTextMins.getText().toString());
			} catch (Exception e) {
				// TODO: handle exception
				timespan_mins = 0;
			}

			if (0 == timespan_hours) {
				if (timespan_mins < SHORTEST_TIMESPAN_MINS) {
					return RESULT_TOO_SMALL;
				} else if (timespan_mins >= SHORTEST_TIMESPAN_MINS
						&& timespan_mins <= LONGEST_TIMESPAN_MINS) {
					return RESULT_RIGHT;
				} else {
					return RESULT_INPUT_ERROR;
				}
			} else {
				if (timespan_mins <= LONGEST_TIMESPAN_MINS) {
					return RESULT_RIGHT;
				} else {
					return RESULT_INPUT_ERROR;
				}
			}
		case MODE_EVERDAY:
			int hours_everday,
			mins_everday;
			try {
				hours_everday = Integer.parseInt(eTextEverydayH.getText()
						.toString());
			} catch (Exception e) {
				// TODO: handle exception
				hours_everday = 0;
			}
			try {
				mins_everday = Integer.parseInt(eTextEverydayM.getText()
						.toString());
			} catch (Exception e) {
				// TODO: handle exception
				mins_everday = 0;
			}
			if (hours_everday <= LONGEST_TIMESPAN_HOURS) {
				if (mins_everday <= LONGEST_TIMESPAN_MINS) {
					return RESULT_RIGHT;
				} else {
					return RESULT_INPUT_ERROR;
				}
			} else {
				return RESULT_INPUT_ERROR;
			}

		default:
			return RESULT_INPUT_ERROR;
		}

	}

	private void writeConfigToLocal(String type, String value) {
		try {
			xmlManager.writeConfig(type, value);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "write config error:" + e.getMessage());
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "write config error:" + e.getMessage());
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void setMode(byte mode) {
		switch (mode) {
		case MODE_TIMESPAN:
			CURRENT_MODE = MODE_TIMESPAN;
			CURRENT_TYPE = XmlManager.TYPE_TIME_SPAN;
			showTimespanView.setBackgroundResource(R.color.lightRed);
			showEveryDayView.setBackgroundResource(R.color.light_gray);
			// eTextEverydayH.setText("");
			// eTextEverydayM.setText("");
			checkTimespan.setVisibility(View.VISIBLE);
			checkTimespan.setChecked(true);
			checkEverday.setVisibility(View.VISIBLE);
			checkEverday.setChecked(false);
			break;
		case MODE_EVERDAY:
			CURRENT_MODE = MODE_EVERDAY;
			CURRENT_TYPE = XmlManager.TYPE_EVERYDAY_TIME;
			showEveryDayView.setBackgroundResource(R.color.lightRed);
			showTimespanView.setBackgroundResource(R.color.light_gray);
			// eTextHours.setText("");
			// eTextMins.setText("");
			checkEverday.setVisibility(View.VISIBLE);
			checkEverday.setChecked(true);
			checkTimespan.setVisibility(View.VISIBLE);
			checkTimespan.setChecked(false);
			break;
		default:
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnSetOK:
			switch (checkInput()) {
			case RESULT_RIGHT:
				if (CURRENT_MODE == MODE_EVERDAY) {
					String everdayH = eTextEverydayH.getText().toString();
					String everdayM = eTextEverydayM.getText().toString();
					if (TextUtils.isEmpty(everdayH)) {
						everdayH = "0";
						eTextEverydayH.setText("00");
					}
					if (TextUtils.isEmpty(everdayM)) {
						everdayM = "0";
						eTextEverydayM.setText("00");
					}
					writeConfigToLocal(CURRENT_TYPE, everdayH
							+ XmlManager.SPLIT + everdayM);
				} else {
					String timespanH = eTextHours.getText().toString();
					String timespanM = eTextMins.getText().toString();
					if (TextUtils.isEmpty(timespanH)) {
						timespanH = "24";
						eTextHours.setText("24");
						Toast.makeText(this, "Default timespan is 24h.",
								Toast.LENGTH_SHORT).show();
					}
					if (TextUtils.isEmpty(timespanM)) {
						timespanM = "0";
						eTextMins.setText("00");
					}
					writeConfigToLocal(CURRENT_TYPE, timespanH
							+ XmlManager.SPLIT + timespanM);
				}

				setResult(ProcessGrid.TIME_SETTING);
				ScheduleService.setRestart(true);
				startService(new Intent(this, ScheduleService.class));
				Toast.makeText(this, "Succeed to save your settings.",
						Toast.LENGTH_LONG).show();
				mHandler.sendEmptyMessageDelayed(MSG_FINISH_ACTIVITY, 1500);
				break;
			case RESULT_TOO_SMALL:
				Toast.makeText(this,
						"Input error, too small, at least 15mins.",
						Toast.LENGTH_LONG).show();
				break;
			case RESULT_INPUT_ERROR:
				switch (CURRENT_MODE) {
				case MODE_TIMESPAN:
					Toast.makeText(this, "Input error, mins between(0-59).",
							Toast.LENGTH_LONG).show();
					break;
				case MODE_EVERDAY:
					Toast
							.makeText(
									this,
									"Input error, mins between(0-59), hours between(0-23)",
									Toast.LENGTH_LONG).show();
				default:
					break;
				}
			default:
				break;
			}
			break;
		case R.id.btnSetCancel:
			finish();
			break;
		default:
			break;
		}
	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_FINISH_ACTIVITY:
				finish();
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}

	};
}
